package com.app.studyroom.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.app.studyroom.R;

public class FloorAdapter extends RecyclerView.Adapter<FloorAdapter.FloorViewHolder> {

    private String[] floors;
    private Context context;
    private OnItemClickListener listener;
    private int selectedPosition = -1; // 新增选中位置变量

    public interface OnItemClickListener {
        void onItemClick(String floor);
    }

    public FloorAdapter(String[] floors, Context context) {
        this.floors = floors;
        this.context = context;
    }

    @NonNull
    @Override
    public FloorViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.floor_item, parent, false);
        return new FloorViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FloorViewHolder holder, int position) {
        holder.textView.setText(floors[position]);

        // 设置选中效果
        holder.itemView.setBackgroundColor(
                position == selectedPosition ? Color.parseColor("#ADD8E6") : Color.TRANSPARENT
        );

        holder.itemView.setOnClickListener(v -> {
            int previousPosition = selectedPosition;
            selectedPosition = position;
            notifyItemChanged(previousPosition);
            notifyItemChanged(selectedPosition);
            listener.onItemClick(floors[position]);
        });
    }

    @Override
    public int getItemCount() {
        return floors.length;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public static class FloorViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public FloorViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.floor_name);
        }
    }
}
